package com.dmap.admin.controller.backgroundv2;

import com.dmap.admin.bo.backgroundv2.ProjectBo;
import com.dmap.admin.constants.AdminConstant;
import com.dmap.admin.controller.backgroundv2.param.ProjectParam;
import com.dmap.admin.controller.backgroundv2.param.ProjectSelectParam;
import com.dmap.admin.po.App;
import com.dmap.admin.po.Device;
import com.dmap.admin.po.DeviceType;
import com.dmap.admin.po.Project;
import com.dmap.admin.service.backgroundv2.AppService;
import com.dmap.admin.service.backgroundv2.DeviceService;
import com.dmap.admin.service.backgroundv2.DeviceTypeService;
import com.dmap.admin.service.backgroundv2.ProjectService;
import com.dmap.admin.vo.backgroundv2.RecordNumAndProjectVo;
import com.dmap.base.constants.Constant;
import com.dmap.base.vo.BaseVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * \* User: helei
 * \* Date: 25/05/18
 * \* Description:
 * \
 */
@Api(value = "个人数据服务系统-项目管理", description = "background/项目管理")
@Controller
@RequestMapping(value = "/background/pmpd-admin-server/v2/project/")
public class ProjectController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private ProjectService projectService;
    @Resource
    private AppService appService;
    @Resource
    private DeviceTypeService deviceTypeService;
    @Resource
    private DeviceService deviceService;

    @ResponseBody
    @ApiOperation(value = "新增 project",
            notes = "1. 必填： appId, deviceTypeId, deviceId, companyId, companyNumber, companyName, companyType, " +
                    " userType, creatorId, creatorAccount; " +
                    "2. 返回id;")
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public BaseVo insert(@RequestBody ProjectParam param) {
        BaseVo baseVo = new BaseVo();
        if (param == null || StringUtils.isBlank(param.getAppId()) || !StringUtils.isNumeric(param.getAppId())
                || Long.valueOf(param.getAppId()).equals(0L)
                || StringUtils.isBlank(param.getDeviceTypeId()) || !StringUtils.isNumeric(param.getDeviceTypeId())
                || Long.valueOf(param.getDeviceTypeId()).equals(0L)
                || StringUtils.isBlank(param.getDeviceId()) || !StringUtils.isNumeric(param.getDeviceId())
                || Long.valueOf(param.getDeviceId()).equals(0L)
                || StringUtils.isBlank(param.getCompanyId()) || !StringUtils.isNumeric(param.getCompanyId())
                || Long.valueOf(param.getCompanyId()).equals(0L)
                || StringUtils.isBlank(param.getCompanyName()) || StringUtils.isBlank(param.getCompanyNumber())
                || StringUtils.isBlank(param.getCreatorId()) || !StringUtils.isNumeric(param.getCreatorId())
                || Long.valueOf(param.getCreatorId()).equals(0L)
                || StringUtils.isBlank(param.getCreatorAccount())
                || param.getCompanyType() == null || param.getUserType() == null
                || param.getCompanyType() == 0 || param.getUserType() == 0) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        //同一个固件只能分配给一家公司
        boolean paramIsExist = projectService.validateDeviceIdIsExist(param.getDeviceId());
        if (paramIsExist) {
            baseVo.setCode(AdminConstant.RESPONSE_DEVICE_PROJECT_UNIQUE_ERROR_CODE);
            baseVo.setMsg(AdminConstant.RESPONSE_DEVICE_PROJECT_UNIQUE_ERROR_MSG);
            return baseVo;
        }
        List<Project> projectList = projectService.selectByAppId(Long.valueOf(param.getAppId()));
        if (CollectionUtils.isNotEmpty(projectList)) {
            for (Project project : projectList) {
                //同一个App只能分配给一家公司
                if (!Long.valueOf(param.getCompanyId()).equals(project.getCompanyId())) {
                    baseVo.setCode(AdminConstant.RESPONSE_APP_PROJECT_UNIQUE_ERROR_CODE);
                    baseVo.setMsg(AdminConstant.RESPONSE_APP_PROJECT_UNIQUE_ERROR_MSG);
                    return baseVo;
                }
            }
        }
        Project insert = projectService.insertProject(param);
        if (insert == null) {
            baseVo.setCode(Constant.RESPONSE_INSERT_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_INSERT_ERROR_MSG);
            return baseVo;
        }
        baseVo.setData(insert.getId().toString());
        return baseVo;
    }

    @ResponseBody
    @ApiOperation(value = "修改 project",
            notes = "1. 必填： id, appId, deviceTypeId, deviceId, companyId, companyNumber, companyName, companyType, " +
                    "  userType, editorId, editorAccount; ")
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public BaseVo update(@RequestBody ProjectParam param) {
        BaseVo baseVo = new BaseVo();
        if (param == null || StringUtils.isBlank(param.getId()) || !StringUtils.isNumeric(param.getId())
                || Long.valueOf(param.getId()).equals(0L)
                || StringUtils.isBlank(param.getAppId()) || !StringUtils.isNumeric(param.getAppId())
                || Long.valueOf(param.getAppId()).equals(0L)
                || StringUtils.isBlank(param.getDeviceTypeId()) || !StringUtils.isNumeric(param.getDeviceTypeId())
                || Long.valueOf(param.getDeviceTypeId()).equals(0L)
                || StringUtils.isBlank(param.getDeviceId()) || !StringUtils.isNumeric(param.getDeviceId())
                || Long.valueOf(param.getDeviceId()).equals(0L)
                || StringUtils.isBlank(param.getCompanyId()) || !StringUtils.isNumeric(param.getCompanyId())
                || Long.valueOf(param.getCompanyId()).equals(0L)
                || StringUtils.isBlank(param.getEditorId()) || !StringUtils.isNumeric(param.getEditorId())
                || Long.valueOf(param.getEditorId()).equals(0L)
                || StringUtils.isBlank(param.getCompanyName()) || StringUtils.isBlank(param.getCompanyNumber())
                || StringUtils.isBlank(param.getEditorAccount())
                || param.getCompanyType() == null || param.getUserType() == null
                || param.getCompanyType() == 0 || param.getUserType() == 0) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        List<Project> projectList = projectService.selectByAppId(Long.valueOf(param.getAppId()));
        if (CollectionUtils.isNotEmpty(projectList)) {
            for (Project project : projectList) {
                if (!Long.valueOf(param.getCompanyId()).equals(project.getCompanyId())) {
                    baseVo.setCode(AdminConstant.RESPONSE_APP_PROJECT_UNIQUE_ERROR_CODE);
                    baseVo.setMsg(AdminConstant.RESPONSE_APP_PROJECT_UNIQUE_ERROR_MSG);
                    return baseVo;
                }
            }
        }
        boolean success;
        try {
            success = projectService.updateProject(param);
        } catch (RuntimeException e) {
            logger.error(e.getMessage());
            baseVo.setCode(AdminConstant.RESPONSE_DEVICE_PROJECT_UNIQUE_ERROR_CODE);
            baseVo.setMsg(AdminConstant.RESPONSE_DEVICE_PROJECT_UNIQUE_ERROR_MSG);
            return baseVo;
        }
        if (!success) {
            baseVo.setCode(Constant.RESPONSE_UPDATE_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_UPDATE_ERROR_MSG);
        }
        return baseVo;
    }

    @ResponseBody
    @ApiOperation(value = "根据参数查询project，和模糊查询、排序是一个接口",
            notes = "1. 必填： companyType; " +
                    "2. 必填： pageIndex(>=1), pageSize(>=1); " +
                    "3. 返回project列表; ")
    @RequestMapping(value = "select/selectByExample", method = RequestMethod.POST)
    public BaseVo selectByExample(@RequestBody ProjectSelectParam param) {
        BaseVo baseVo = new BaseVo();
        if (param == null || param.getCompanyType() == null
                || param.getCompanyType() != AdminConstant.COMPANY_TYPE_HEAD
                || param.getPageIndex() == null || param.getPageSize() == null
                || param.getPageIndex() < 1 || param.getPageSize() < 1) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        int recordNum = projectService.countByProjectSelectParam(param);
        List<ProjectBo> boList = new ArrayList<>();
        if (recordNum > 0) {
            boList = projectService.selectByProjectSelectParam(param);
        }
        RecordNumAndProjectVo returnVo = new RecordNumAndProjectVo(recordNum, boList);
        baseVo.setData(returnVo);
        return baseVo;
    }

    @ResponseBody
    @ApiOperation(value = "根据id查询project", notes = "1. 必填： id;")
    @RequestMapping(value = "select/selectById", method = RequestMethod.GET)
    public BaseVo selectById(@RequestParam String id) {
        BaseVo baseVo = new BaseVo();
        if (StringUtils.isBlank(id) || !StringUtils.isNumeric(id) || Long.valueOf(id).equals(0L)) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        Project project = projectService.selectById(Long.valueOf(id));
        List<ProjectBo> boList = new ArrayList<>();
        if (project != null) {
            ProjectBo bo = new ProjectBo(project);
            App app = appService.selectById(project.getAppId());
            if (app != null) {
                bo.setProjectId(app.getProjectId());
                bo.setProjectName(app.getProjectName());
                bo.setAppImageUrl(app.getAppImageUrl());
            }
            DeviceType deviceType = deviceTypeService.selectById(project.getDeviceTypeId());
            if (deviceType != null) {
                bo.setTypeNumber(deviceType.getTypeNumber());
                bo.setTypeName(deviceType.getTypeName());
                bo.setTypeImageUrl(deviceType.getTypeImageUrl());
            }
            Device device = deviceService.selectById(project.getDeviceId());
            if (device != null) {
                bo.setFirmware(device.getFirmware());
                bo.setDeviceName(device.getDeviceName());
                bo.setDeviceImageUrl(device.getDeviceImageUrl());
            }
            boList.add(bo);
        }
        RecordNumAndProjectVo recordNumAndProjectVo = new RecordNumAndProjectVo(1, boList);
        baseVo.setData(recordNumAndProjectVo);
        return baseVo;
    }

}